package com.example.donghuihui.androidframe.basewebview;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.view.View;
import android.webkit.WebView;
import android.widget.AbsoluteLayout.LayoutParams;
import android.widget.ProgressBar;

import com.example.donghuihui.androidframe.R;


public class BaseWebChromeClient extends android.webkit.WebChromeClient {

    private ProgressBar progressBar;
    private boolean flag = false;
    private Handler handler = new Handler();
    int progress = 0;

    @SuppressWarnings("deprecation")
    public BaseWebChromeClient(Context context, BaseWebView webView) {
        progressBar = new ProgressBar(context, null,
                android.R.attr.progressBarStyleHorizontal);
        progressBar.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
                5, 0, 0));
        Drawable drawable = context.getResources().getDrawable(
                R.drawable.webview_progress_drawable);
        progressBar.setProgressDrawable(drawable);
        webView.addView(progressBar);
    }

    @SuppressWarnings("deprecation")
    public BaseWebChromeClient(Context context, WebView webView) {
        progressBar = new ProgressBar(context, null,
                android.R.attr.progressBarStyleHorizontal);
        progressBar.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
                5, 0, 0));
        Drawable drawable = context.getResources().getDrawable(
                R.drawable.webview_progress_drawable);
        progressBar.setProgressDrawable(drawable);
        webView.addView(progressBar);
    }

    @Override
    public void onProgressChanged(WebView view, int newProgress) {
        if (newProgress == 100) {
            progressBar.setVisibility(View.GONE);
        } else {
            if (progressBar.getVisibility() == View.GONE) {
                progressBar.setVisibility(View.VISIBLE);
            }
            if (!flag) {
                setProgressBarFirst();
            } else {
                if (newProgress >= progress) {
                    progressBar.setProgress(newProgress);
                } else {
                    progressBar.setProgress((int) (newProgress / 100) * 20 + 80);
                }
            }
        }
        super.onProgressChanged(view, newProgress);
    }

    private void setProgressBarFirst() {
        handler.postDelayed(runnable, 10);
    }

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            // 这里再次调用此Runnable对象，以实现每两秒实现一次的定时器操作
            progressBar.setProgress(progress);
            if (progress >= 80) {
                flag = true;
                handler.removeCallbacks(runnable);
            } else {
                progress += 1;
                handler.postDelayed(this, 10);
            }

        }
    };

}
